﻿using Identity.API.Model;
using Identity.API.ViewModel;
using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace Identity.API.Controllers
{

    [Route("api/v1/userinfo")]
    //[Authorize]
    [ApiController]
    public class UserInfoController : ControllerBase
    {
        private readonly IUserInfoRepository _userRepository;

        public UserInfoController(
            IUserInfoRepository userRepository)
        {
            _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
        }

        [Route("add")]
        [HttpPost]
        public async Task<IActionResult> Create(UserInfoViewModel user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (string.IsNullOrWhiteSpace(user.OpenId))
            {
                return BadRequest("无微信信息。");
            }
            if (string.IsNullOrWhiteSpace(user.Name))
            {
                return BadRequest("未填写名称。");
            }
            var openUser = await _userRepository.GetUserInfoByOpenIdAsync(user.OpenId);
            if (openUser != null)
            {
                return BadRequest("该微信已注册。");
            }

            var userinfo = new UserInfo() { OpenId = user.OpenId, Name = user.Name, LastDate = DateTime.Now };
            var result = await _userRepository.AddOrGetUserInfoAsync(userinfo);

            return Ok(result);
        }

        [Route("{openId}/ByOpenId")]
        [HttpGet]
        public async Task<UserInfoViewModel> GetByOpenIdAsync(string openId)
        {
            var user = await _userRepository.GetUserInfoByOpenIdAsync(openId);

            if (user == null)
            {
                return null;
            }
            else
            {
                return new UserInfoViewModel() { Id = user.Id, OpenId = user.OpenId, Name = user.Name };
            }
        }
    }
}
